package com.isman.placeslist;

import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isman.placeslist.apiobject.Status;
import com.isman.placeslist.util.Util;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class PageStatus extends Activity {
	public static final String STATUS_INFO = "StatusInfo";
	public static final String STATUS_INDEX = "StatusIndex";
	public static final int STATUS_DETAIL = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_status);
		mStatus = (Status) getIntent().getExtras().getSerializable(STATUS_INFO);
		mUpdateResult();

		init();
		mLoadComment();
		mResourceStatus();
		mUpdateStatus();
		mCommentAdapter = new CommentAdapter(this);
		vLvListComment.setAdapter(mCommentAdapter);
		mCommentAdapter.notifyDataSetChanged();

	}

	private void init() {
		vPgbLoadLikeStatus = (ProgressBar) findViewById(R.id.pgb_head_load);
		vEtInputComment = (EditText) findViewById(R.id.et_status_input);
		vLvListComment = (ListView) findViewById(R.id.lvw_comment_list);
		vIbtnSendComment = (ImageButton) findViewById(R.id.ibtn_status_send);
		vTbtnStatusLike = (ToggleButton) findViewById(R.id.tbtn_status_like);

		vTbtnStatusLike.setChecked(!mStatus.isCanLike());
		vIbtnSendComment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mComment();
			}
		});
		vTbtnStatusLike
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean ckeck) {
						if (ckeck) {
							mStatusLike();
						} else {
							mStatusUnlike();
						}
					}
				});
	}

	private void mResourceStatus() {
		switch (mStatus.getStatusType()) {
		case 0:
		case 1:
			vViewStatus = LayoutInflater.from(this).inflate(
					R.layout.inc_item_status_normal, null);
			break;
		case 2:
			vViewStatus = LayoutInflater.from(this).inflate(
					R.layout.inc_item_status_checkin, null);
			break;
		}

		vlblStatusMessage = (TextView) vViewStatus
				.findViewById(R.id.lbl_item_status_message);
		vlblStatusCreate = (TextView) vViewStatus
				.findViewById(R.id.lbl_item_status_createtime);
		vlblStatusName = (TextView) vViewStatus
				.findViewById(R.id.lbl_item_status_profilename);
		vlblStatusLike = (TextView) vViewStatus
				.findViewById(R.id.lbl_item_status_likeCount);
		mAddHeader();
	}

	private void mAddHeader() {
		vViewStatus.setBackgroundColor(0xFFFFFFFF);
		vLvListComment.addHeaderView(vViewStatus);
	}

	private void mUpdateStatus() {

		if (mStatus.getFrom().getPicture() != "") {
			new Thread(new Runnable() {
				@Override
				public void run() {
					final Bitmap bmp = Util.getBitmap(mStatus.getFrom()
							.getPicture());

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ImageView vimgStatusProfile = (ImageView) findViewById(R.id.img_item_status_profileimage);
							vimgStatusProfile.setImageBitmap(bmp);
						}
					});
				}
			}).run();
		}

		if (mStatus.getStatusType() == 1) {
			final ImageView vImgImage = (ImageView) findViewById(R.id.img_item_status_image_priview);
			new Thread(new Runnable() {
				@Override
				public void run() {
					final Bitmap bmp = Util.getBitmap(mStatus.getImage()
							.getSize120());
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							vImgImage.setImageBitmap(bmp);
							vImgImage.setVisibility(View.VISIBLE);
						}
					});
				}
			}).run();
		}

		if (mStatus.getCurrentLocation() != null) {
			TextView vlblCurrent = (TextView) findViewById(R.id.lbl_item_status_current);
			vlblCurrent.setText("@" + mStatus.getCurrentLocation());
		}

		if (mStatus.getLikeCount() != 0) {
			vlblStatusLike.setVisibility(View.VISIBLE);
			if (mStatus.getLikeCount() == 1) {
				vlblStatusLike.setText(mStatus.getLikeCount() + " people");
			} else if (mStatus.getLikeCount() > 1) {
				vlblStatusLike.setText(mStatus.getLikeCount() + " peoples");
			}
		} else {
			vlblStatusLike.setVisibility(View.GONE);
		}

		vlblStatusMessage.setText(mStatus.getMessage());
		vlblStatusCreate.setText(mStatus.getCreateTime());
		vlblStatusName.setText(mStatus.getFrom().getName());
	}

	private void mLoadComment() {
		vPgbLoadLikeStatus.setVisibility(View.VISIBLE);
		ServiceProvider provider = new ServiceProvider(this);
		provider.LoadComment(mStatus.getId(), new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				Type type = new TypeToken<ArrayList<Status>>() {
				}.getType();
				final ArrayList<Status> mCC = new Gson().fromJson(json, type);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mCommentList.addAll(mCC);
						mCommentAdapter.notifyDataSetChanged();
						vPgbLoadLikeStatus.setVisibility(View.GONE);
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}

			@Override
			public void onError(int statusCode, String json) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}

			@Override
			public void onConnectingError(String message) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}
		});
	}

	private void mComment() {
		vPgbLoadLikeStatus.setVisibility(View.VISIBLE);
		vEtInputComment.setEnabled(false);
		vIbtnSendComment.setEnabled(false);
		ServiceProvider provider = new ServiceProvider(this);
		provider.CreateComment(mStatus.getId(), vEtInputComment.getText()
				.toString(), new AsyncRunnerHeadler() {
			@Override
			public void onComplete(final String json) {
				final Status statu = new Gson().fromJson(json, Status.class);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						vEtInputComment.setEnabled(true);
						vIbtnSendComment.setEnabled(true);
						vEtInputComment.setText("");
						vPgbLoadLikeStatus.setVisibility(View.GONE);

						mCommentList.add(statu);
						mCommentAdapter.notifyDataSetChanged();
						mStatus.setChildCount(mCommentList.size());
						mUpdateResult();
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}

			@Override
			public void onError(int statusCode, String json) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}

			@Override
			public void onConnectingError(String message) {
				vPgbLoadLikeStatus.setVisibility(View.GONE);
			}
		});
	}

	private void mStatusLike() {
		vTbtnStatusLike.setEnabled(false);
		ServiceProvider provider = new ServiceProvider(this);
		provider.StatusLike(mStatus.getId(), new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						vTbtnStatusLike.setEnabled(true);
						mStatus.setCanLike(false);
						mStatus.setLikeCount(mStatus.getLikeCount() + 1);
						mUpdateStatus();
						mUpdateResult();
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				Toast.makeText(PageStatus.this, "Like error", Toast.LENGTH_LONG)
						.show();
			}

			@Override
			public void onError(int statusCode, String json) {
				Toast.makeText(PageStatus.this, "Like error", Toast.LENGTH_LONG)
						.show();
			}

			@Override
			public void onConnectingError(String message) {
				Toast.makeText(PageStatus.this, "Like error", Toast.LENGTH_LONG)
						.show();
			}
		});
	}

	private void mStatusUnlike() {
		vTbtnStatusLike.setEnabled(false);
		ServiceProvider provider = new ServiceProvider(this);
		provider.StatusUnlike(mStatus.getId(), new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						vTbtnStatusLike.setEnabled(true);
						mStatus.setCanLike(true);
						mStatus.setLikeCount(mStatus.getLikeCount() - 1);
						mUpdateStatus();
						mUpdateResult();
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
			}

			@Override
			public void onError(int statusCode, String json) {
			}

			@Override
			public void onConnectingError(String message) {
			}
		});
	}

	private void mUpdateResult() {
		mData = new Intent();
		mData.putExtra(STATUS_INDEX, mIndex);
		mData.putExtra(STATUS_INFO, mStatus);
		setResult(RESULT_FIRST_USER, mData);
	}

	public class CommentAdapter extends BaseAdapter {
		private Activity mActivity;

		public CommentAdapter(Activity mActivity) {
			mInflater = LayoutInflater.from(mActivity);
			this.mActivity = mActivity;
		}

		@Override
		public int getCount() {
			return mCommentList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mCommentList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(final int index, View arg1, ViewGroup arg2) {
			final Status mComment = mCommentList.get(index);
			View mView = mInflater.inflate(R.layout.inc_item_comment, null);

			if (index % 2 == 0) {
				mView.setBackgroundColor(0xFFEFEFEF);
			} else {
				mView.setBackgroundColor(0xFFFFFFFF);
			}

			TextView vlblName = (TextView) mView
					.findViewById(R.id.lbl_item_comment_profilename);
			TextView vlblTime = (TextView) mView
					.findViewById(R.id.lbl_item_comment_createtime);
			TextView vlblMess = (TextView) mView
					.findViewById(R.id.lbl_item_comment_message);
			TextView vlblCount = (TextView) mView
					.findViewById(R.id.lbl_item_comment_likeCount);
			Button vbtnDelete = (Button) mView
					.findViewById(R.id.btn_item_comment_delete);
			final ToggleButton vtbtnCLike = (ToggleButton) mView
					.findViewById(R.id.tbtn_item_comment_like);
			final ImageView vimgCProfile = (ImageView) mView
					.findViewById(R.id.img_item_comment_profile);
			new Thread(new Runnable() {
				@Override
				public void run() {
					final Bitmap bmp = Util.getBitmap(mComment.getFrom()
							.getPicture());
					mActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							vimgCProfile.setImageBitmap(bmp);
						}
					});
				}
			}).run();

			if (mComment.getLikeCount() > 0) {
				vlblCount.setVisibility(View.VISIBLE);
				if (mComment.getLikeCount() == 1) {
					vlblCount.setText(mComment.getLikeCount() + " people");
				} else {
					vlblCount.setText(mComment.getLikeCount() + " peoples");
				}
			} else {
				vlblCount.setVisibility(View.GONE);
			}
			vlblMess.setText(mComment.getMessage());
			vlblName.setText(mComment.getFrom().getName());
			vlblTime.setText(mComment.getCreateTime());

			vtbtnCLike.setChecked(!mComment.isCanLike());
			vtbtnCLike
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean check) {
							if (check) {
								mLikeComment(mComment, index, vtbtnCLike);
							} else {
								mUnlikeComment(mComment, index, vtbtnCLike);
							}
						}
					});
			vbtnDelete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (mComment.isCanDelete()) {
						mDeleteDialog(mComment, index);
					} else {
						// mReportDialog(mComment,index);
					}
				}
			});
			return mView;
		}

		private void mLikeComment(final Status mComment, final int index,
				final ToggleButton vbtnCommentLike) {
			vbtnCommentLike.setEnabled(false);
			ServiceProvider provider = new ServiceProvider(mActivity);
			provider.CommentLike(mComment.getId(), new AsyncRunnerHeadler() {
				@Override
				public void onComplete(String json) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							vbtnCommentLike.setEnabled(true);
							mComment.setCanLike(false);
							mComment.setLikeCount(mComment.getLikeCount() + 1);
							mCommentList.set(index, mComment);
							mCommentAdapter.notifyDataSetChanged();
						}
					});
				}

				@Override
				public void onAuthenticate(String json) {
				}

				@Override
				public void onError(int statusCode, String json) {
				}

				@Override
				public void onConnectingError(String message) {
				}
			});
		}

		private void mUnlikeComment(final Status mComment, final int index,
				final ToggleButton vbtnCommentLike) {
			vbtnCommentLike.setEnabled(false);
			ServiceProvider provider = new ServiceProvider(mActivity);
			provider.CommentUnlike(mComment.getId(), new AsyncRunnerHeadler() {
				@Override
				public void onComplete(String json) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							vbtnCommentLike.setEnabled(true);
							mComment.setCanLike(true);
							mComment.setLikeCount(mComment.getLikeCount() - 1);
							mCommentList.set(index, mComment);
							mCommentAdapter.notifyDataSetChanged();
						}
					});
				}

				@Override
				public void onAuthenticate(String json) {
				}

				@Override
				public void onError(int statusCode, String json) {
				}

				@Override
				public void onConnectingError(String message) {
				}
			});
		}

		private void mDeleteComment(Status comment, final int index) {
			vPgbLoadLikeStatus.setVisibility(View.VISIBLE);
			ServiceProvider provider = new ServiceProvider(mActivity);
			provider.DeleteComment(comment.getId(), new AsyncRunnerHeadler() {
				@Override
				public void onComplete(String json) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mCommentList.remove(index);
							mStatus.setChildCount(mCommentList.size());
							mCommentAdapter.notifyDataSetChanged();
							vPgbLoadLikeStatus.setVisibility(View.GONE);
						}
					});
				}

				@Override
				public void onAuthenticate(String json) {
				}

				@Override
				public void onError(int statusCode, String json) {
				}

				@Override
				public void onConnectingError(String message) {
				}
			});
		}

		private void mReportComment(Status comment, final int index) {
			Toast.makeText(mActivity, "Report", Toast.LENGTH_LONG).show();
		}

		private void mDeleteDialog(final Status comment, final int index) {
			AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
			builder.setMessage("Are you sure you want to delete?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									mDeleteComment(comment, index);
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			builder.create().show();
		}

		private void mReportDialog(final Status comment, final int index) {
			AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
			builder.setMessage("Are you sure you want send report?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									mReportComment(comment, index);
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			builder.create().show();
		}

		private LayoutInflater mInflater;
	}

	private ArrayList<Status> mCommentList = new ArrayList<Status>();
	private Status mStatus;
	private Intent mData;
	private int mIndex;
	private CommentAdapter mCommentAdapter;

	private View vViewStatus;
	private ProgressBar vPgbLoadLikeStatus;
	private ImageButton vIbtnSendComment;
	private ToggleButton vTbtnStatusLike;
	private EditText vEtInputComment;
	private ListView vLvListComment;

	private TextView vlblStatusMessage;
	private TextView vlblStatusCreate;
	private TextView vlblStatusName;
	private TextView vlblStatusLike;
}
